/* eslint-disable */
/**
 * 华为云OBS
 */
import { GetResourceConfig } from '@/api/common.js'
const { v4: uuidv4 } = require('uuid');
// 初始化Obs客户端
function getObsClient(ak, sk, upToken, server) {
  const obsClient = new ObsClient({
    access_key_id: ak,
    secret_access_key: sk,
    server: server,
    security_token: upToken,
    timeout: 60 * 5
  })
  return obsClient
}
// 上传文件
/**
 *
 * @param {file||Blob} file 文件对象
 * @param {string} menu 模块名
 * @param {string} fileName 文件名
 * @param {Function} cb 上传进度
 */
export function upFile(file, menu, fileName, cb) {
  return new Promise((resolve, reject) => {
    getFileInfo(file)
      .then(data => {
        GetResourceConfig().then(res => {
          const { accessKeyID, accessKeySecret, upToken, bucket, domain, endPoint } = res.data
          const Key = `${process.env.NODE_ENV === 'production' ? '' : 'dev/'}${menu}/${fileName}_${new Date().getTime()}.${data.suffix}`

          getObsClient(accessKeyID, accessKeySecret, upToken, endPoint).putObject(
            {
              Bucket: bucket, // 桶名
              Key: Key, // 文件名
              SourceFile: file, // Blob对象或file对象
              ProgressCallback: cb
            },
            function(err, result) {
              if (err) reject('[OBS Error] upfile error!')

              const rdata = {}
              rdata.fileName = '/' + Key
              rdata.domain = domain
              rdata.fileWidth = data.w
              rdata.fileHeight = data.h
              rdata.suffix = data.suffix
              rdata.mimeType = data.mimeType // 文件类型  1 视频    2图片
              if (data.duration) rdata.duration = parseInt(data.duration) //视频时长  保留整数
              resolve(rdata)
            }
          )
        })
      })
      .catch(e => {
        reject(e)
      })
  })
}

/**
 * 上传apk
 * @param {file||Blob} file 文件对象
 * @param {Function} cb 上传进度
 */
export function upApk(path, file, cb) {
  return new Promise((resolve, reject) => {
    GetResourceConfig().then(res => {
      const { accessKeyID, accessKeySecret, upToken, bucket, endPoint } = res.data
      const Key = `${process.env.NODE_ENV === 'production' ? '' : 'dev/'}${path}`
      getObsClient(accessKeyID, accessKeySecret, upToken, endPoint).putObject(
        {
          Bucket: bucket, // 桶名
          Key: Key, // 文件名
          SourceFile: file, // Blob对象或file对象
          ProgressCallback: cb
        },
        function(err, result) {
          if (err) reject('[OBS Error] upfile error!' + err)
          const rdata = {}
          rdata.url = 'https://apk.kktv6.com/' + Key
          resolve(rdata)
        }
      )
    })
  })
}

/**
 * @param {file||Blob} file 文件对象
 * @param {Function} cb 上传进度
 */
export function upExcelFile(file, cb) {
  console.log('upExcelFile-file=',file)
  return new Promise((resolve, reject) => {
    GetResourceConfig().then(res => {
      const { access, secret, securityToken, huaWeiBucket, server,privacyData } = res.data
      const arr = file.name.split(".")
      const Key = privacyData+'/'+Date.now()+uuidv4()+'.'+arr[arr.length-1]
      getObsClient(access, secret, securityToken, server).putObject(
        {
          Bucket: huaWeiBucket, // 桶名
          Key: Key, // 文件名
          SourceFile: file, // Blob对象或file对象
          ProgressCallback: cb,
          Expires:1//天  7
        },
        function(err, result) {
          console.log('putObject=',err,result)
          if (err) reject('[OBS Error] upfile error!' + err)
          const url = 'https://kktv9-test.obs.cn-east-2.myhuaweicloud.com/' + Key
          resolve(url)
        }
      )
    })
  })
}

// 获取file信息
export function getFileInfo(fileObj) {
  if (fileObj.type && fileObj.type.match(/video/)) {
    return new Promise(function(resolve, reject) {
      if (fileObj.type !== 'video/mp4') {
        reject('请上传正确的视频文件类型')
      }

      if (fileObj.size > 200 * 1024 * 1024) {
        reject('视频文件过大')
      }

      // 获取上传的视频的宽高
      const videoUrl = URL.createObjectURL(fileObj)
      const videoObj = document.createElement('video')

      videoObj.onloadedmetadata = function(evt) {
        URL.revokeObjectURL(videoUrl)
        resolve({
          w: videoObj.videoWidth,
          h: videoObj.videoHeight,
          duration: videoObj.duration,
          suffix: fileObj.type.substring(fileObj.type.indexOf('/') + 1),
          mimeType: 1
        })
      }

      videoObj.src = videoUrl
      videoObj.load()
    })
  } else if (fileObj.type && fileObj.type.match(/image/)) {
    return new Promise(function(resolve, reject) {
      // 获取上传的图片的宽高
      const reader = new FileReader()
      reader.readAsDataURL(fileObj)
      reader.onload = function(evt) {
        const replaceSrc = evt.target.result

        const imageObj = new Image()
        imageObj.src = replaceSrc
        imageObj.onload = function() {
          resolve({
            w: imageObj.width,
            h: imageObj.height,
            suffix: fileObj.type.substring(fileObj.type.indexOf('/') + 1),
            mimeType: 2
          })
        }
      }
    })
  } else {
    return new Promise.reject('不支持该文件格式上传！')
  }
}
// 时长转换
function durationTrans(a) {
  let b = ''
  let h = parseInt(a / 3600)
  let m = parseInt((a % 3600) / 60)
  let s = parseInt((a % 3600) % 60)
  if (h > 0) {
    h = h < 10 ? '0' + h : h
    b += h + ':'
  }
  m = m < 10 ? '0' + m : m
  s = s < 10 ? '0' + s : s
  b += m + ':' + s
  return b
}
